package com.ljy.jymail.ware.listener;

import com.ljy.common.to.mq.StockLockedTo;
import com.ljy.jymail.ware.service.WareSkuService;
import com.ljy.common.to.mq.OrderTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/*库存释放Listener*/
@RabbitListener(queues = "stock.release.stock.queue")
@Service
@Slf4j
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /*
     * 监听释放库存的队列的消息
     *
     * 1、库存自动解锁：下单成功，但是其他业务失败导致回滚
     * 2、由于锁库存失败导致回滚，此时库存工作单的数据也会回滚
     *
     * 如果解锁库存的消息失败，一定要告诉服务器解锁失败---启动手动ack机制
     * */
    @RabbitHandler
    public void handlerStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {

        log.info("订单过期，解放库存");
        try{
           wareSkuService.unlockStock(to);
           channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
       }catch (Exception e) {
           //拒绝消息，重新回队
           channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
       }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) throws IOException {
        log.info("接收到订单关闭的信息，准备解锁库存");
            try {
                wareSkuService.unlockStock(to);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }catch (Exception e) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }


    }
}
